class MusicsController < ApplicationController
  skip_before_action :authenticate_request, only:[:index, :show]
  def index
    obj_return(Music.all, status:200)
  end

  def create
    #if Music.find_by(title: params[:data][:attributes][:name])
    #  api_error(:created, status: 201)
    #else
    #@music = Music.new(title: params[:data][:attributes][:name], length: 100, album_id: 2)
    #@music.save!
    #end
    #puts params.to_unsafe_h
    #puts params.each(:data) 
  #  document = JSONAPI.parse(params.to_unsafe_h)
  #  puts document.data.attributes.defined?(:name)
    document = JSONAPI.parse(params.to_unsafe_h)
    @music = Music.new(title: document.data.attributes.title, length: document.data.attributes.length,album_id:2)
    @music.singers << Singer.find(document.data.attributes.singer)
    @music.save!
    obj_return(@music, status: 201)
  end

  def show
    @music = Music.find(params[:id])
    obj_return(@music, status:200)
  end

  def destroy
    @music = Music.find(params[:id])
    @music.destroy
    err_return(:ok, status: 200)
  end

  def update
    @music = Music.find(params[:id])
    document = JSONAPI.parse(params.to_unsafe_h)
    @music.title = document.data.attributes.title if document.data.attributes.defined?(:title)
    @music.length = document.data.attributes.length if document.data.attributes.defined?(:length)
    @music.album_id = document.data.attributes.album_id if document.data.attributes.defined?(:album_id)
    @music.url = document.data.attributes.url if document.data.attributes.defined?(:url)
    @music.save!
    if document.data.attributes.defined?(:singers)
      @music.singers.delete(@music.singers)
      @music.singers << Singer.find(document.data.attributes.singers)
    end
    obj_return(@music, status: 200)
  end

end
